package com.ts.zuul.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.ribbon.RibbonHttpResponse;
import org.springframework.stereotype.Component;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.UUID;


/**
 * Created by Zhou_Bing on 2018/9/6.
 */
@Component
public class ResLogFilter extends ZuulFilter{

    private static final Logger logger =LoggerFactory.getLogger(ResLogFilter.class);

    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 100;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {

        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String reqId = (String) request.getAttribute("reqId");

        InputStream stream = ctx.getResponseDataStream();
        try {
            if(stream!=null){
                BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
                String line = "";
                StringBuilder body = new StringBuilder();
                while((line = reader.readLine()) != null){//一行一行的读取body体里面的内容；
                    body.append(line);
                }
                logger.info("response "+reqId+":: body:"+body.toString());
                ctx.setResponseBody(body.toString());
            }else{
                logger.info("response "+reqId+":: body:"+ctx.getResponseBody());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
